package net.cardgame.orcalecard;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.common.ThreadLoadImage;
import net.cardgame.oraclecard.service.DownloadUnzipObject;
import net.cardgame.oraclecard.service.ServiceDownload;
import net.cardgame.oraclecard.service.ServiceDownloadListener;
import net.cardgame.orcalecard.bean.DeckBean;
import net.cardgame.orcalecard.bean.SettingApp;
import net.cardgame.orcalecard.pref.SecurePreferences;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.NetworkUtils;
import net.cardgame.orcalecard.utils.Sort;
import net.cardgame.orcalecard.utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Top Page Screen
 */
public class TopPageActivity extends Activity implements OnClickListener,
		OnItemClickListener, ServiceDownloadListener {
	private static final int HELP_REQUESTCODE = 0;
	private static final int RANDOM_REQUESTCODE = 1;
	private static final int INFO_DECK_REQUESTCODE = 2;
	private static final int SETTING_REQUESTCODE = 3;
	private static final int HISTORY_REQUESTCODE = 4;
	GridView gridView;
	Intent _i;
	boolean cancel;
	ArrayList<DeckBean> listDeckBean;
	GridViewAdapter adapter;
	int selectedPosition = 1000;
	SettingApp setting;
	SecurePreferences appPreferences;
	boolean flag = true;
	private ProgressDialog pDialog;

	// public final static String KEY_TOPPAGE = "toppage";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.top_activity_layout);
		gridView = (GridView) findViewById(R.id.grid_view_flash);
		findViewById(R.id.icon_help_top).setOnClickListener(this);
		findViewById(R.id.btn_home_toppage).setOnClickListener(this);
		findViewById(R.id.btn_history_toppage).setOnClickListener(this);
		findViewById(R.id.btn_setting_toppage).setOnClickListener(this);
		// init shared reference
		appPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		getStatus();
		loadSettingApp();
		adapter = new GridViewAdapter(this, listDeckBean);
		adapter.registryBroadcast();
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(this);

		if (NetworkUtils.isNetworkConnected(this)
				&& getIntent().getExtras() != null) {
			handlerLoadImage.postDelayed(resumeDownload, 1000);
			// resumeDownload();
		}
	}

	Runnable resumeDownload = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			resumeDownload();
		}
	};

	void getStatus() {
		Gson gson = new Gson();
		Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() {
		}.getType();
		String listSaved = appPreferences
				.getString(ConstantValue.CONFIG_DECKBEAN_KEY);
		listDeckBean = gson.fromJson(listSaved, listOfDeckBean);
	}

	private void startDownloadService(DeckBean deckBean, int position) {
		String id = deckBean.deckId < 10 ? "0" + deckBean.deckId : ""
				+ deckBean.deckId;
		Intent intentService = new Intent(this, ServiceDownload.class);
		intentService.putExtra(ServiceDownload.KEY_DECK_ID, deckBean.deckId);
		intentService.putExtra(ServiceDownload.KEY_PATH_SERVER,
				deckBean.pathServerDownload + ".zip");
		intentService.putExtra(ServiceDownload.KEY_POSITION, position);
		intentService.putExtra(ServiceDownload.KEY_PATH_SAVE,
				ConstantValue.getPatchCardData(this) + "Card_" + id + ".zip");
		startService(intentService);
	}

	void resumeDownload() {
		int i = 0;
		for (DeckBean deckBean : listDeckBean) {
			if (deckBean.percentDownloaded >= 0
					&& deckBean.percentDownloaded < 100) {
				adapter.setPercentDownloaded(i, deckBean.percentDownloaded);
				startDownloadService(deckBean, i);
				showDialogDownload();
				return;
			}
			i++;
		}
	}

	void loadSettingApp() {
		Gson gson = new Gson();
		Type SettingAppType = new TypeToken<SettingApp>() {
		}.getType();
		if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) {
			String strSetting = appPreferences
					.getString(ConstantValue.SETTING_KEY);
			setting = gson.fromJson(strSetting, SettingAppType);
		}
		switch (setting.sortToppage) {
		case SettingApp.SORT_BY_BUY:
			listDeckBean = Sort.sortByBuy(listDeckBean);
			break;
		case SettingApp.SORT_BY_RELEASE:
			listDeckBean = Sort.sortByRelease(listDeckBean);
			break;
		case SettingApp.SORT_BY_USED:
			listDeckBean = Sort.sortByLastUsed(listDeckBean);
			break;
		default:
			break;
		}
	}

	/**
	 * goto InfoDeck activity
	 * 
	 * @param dec
	 */
	public void passDeck(DeckBean dec) {
		if (dec.deckId == 999 || dec.deckId == 998
				|| appPreferences.containsKey("content_" + dec.deckId)
				|| NetworkUtils.isNetworkConnected(this)) {
			Intent i = new Intent(this, InfoDeckActivity.class);
			i.putExtra("deckId", dec.deckId);
			i.putExtra("deckName", dec.deckName);
			i.putExtra("deckPrice", dec.deckPrice);
			i.putExtra("deckPathServer", dec.pathServerDownload);
			i.putExtra("position", selectedPosition);
			i.putExtra("isUnlock", dec.isUnlock);
			i.putExtra("isFree", dec.isFree);
			i.putExtra("inAppPurchaseId", dec.inAppPurchaseId);
			i.putExtra("releaseDate", dec.releaseDate.getTime());
			startActivityForResult(i, INFO_DECK_REQUESTCODE);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
		} else {
			flag = true;
			showDialogSetting();
		}
	}

	public void passDeckToCardDeckActivity(DeckBean dec) {
		_i = new Intent(this, CardDeckActivity.class);
		_i.putExtra("deckId", dec.deckId);
		_i.putExtra("deckName", dec.deckName);
		_i.putExtra("deckPrice", dec.deckPrice);
		_i.putExtra("deckPathServer", dec.pathServerDownload);
		_i.putExtra("position", selectedPosition);
		_i.putExtra("isUnlock", dec.isUnlock);
		_i.putExtra("cardTotal", dec.cardNumber);
		if (dec.deckId == 999) {
			startActivity(_i);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			this.finish();
			return;
		}
		String tt = dec.deckId < 10 ? "0" + dec.deckId : "" + dec.deckId;
		new ThreadLoadImage(this, handlerLoadImage,
				ConstantValue.getPatchCardData(this) + "Card_" + tt + "/en_c"
						+ tt + "t.png", null, 1).start();
	}

	private Handler handlerLoadImage = new Handler() {
		public void handleMessage(Message msg) {
			startActivity(_i);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			TopPageActivity.this.finish();
		};
	};

	public void passHelpType(int iType) {
		Intent i = new Intent(this, HelpActivity.class);
		i.putExtra("indexTypeHelp", iType);
		startActivityForResult(i, HELP_REQUESTCODE);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	/*
	 * Receive result from another activity
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		switch (requestCode) {
		case HISTORY_REQUESTCODE:

			break;
		case HELP_REQUESTCODE:

			break;
		case SETTING_REQUESTCODE:
			if (resultCode == RESULT_OK) {
				getStatus();
				adapter.updateStatus(listDeckBean);
			}
			break;
		case INFO_DECK_REQUESTCODE:
			if (resultCode == RESULT_OK) {
				int positionDownload = data.getExtras().getInt("position");
				if (data.getExtras().containsKey("isUnlock")) {
					Utils.ELog("unlock deckbeans", "ok");
					boolean isUnlock = data.getExtras().getBoolean("isUnlock");
					listDeckBean.get(positionDownload).isUnlock = isUnlock;
					adapter.updateStatus(listDeckBean);
					saveStatus();
				} else {
					Utils.ELog("unlock deckbeans", "no");
					if (!listDeckBean.get(positionDownload).isFree) {
						listDeckBean.get(positionDownload).isUnlock = true;
					}
					listDeckBean.get(positionDownload).percentDownloaded = 0;
					listDeckBean.get(positionDownload).buyDate = new Date();
					adapter.setPercentDownloaded(positionDownload, 0);
					adapter.unlockDeckBean(positionDownload);
					saveStatus();
					showDialogDownload();
				}
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		adapter.unRegistryBroadcast();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (!flag)
			return;
		switch (v.getId()) {
		case R.id.icon_help_top:
			passHelpType(0);
			flag = false;
			break;
		case R.id.btn_home_toppage:
			backtoMainActivity();
			break;
		case R.id.btn_setting_toppage:
			Intent intent2 = new Intent(this, SettingActiviy.class);
			startActivityForResult(intent2, SETTING_REQUESTCODE);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			flag = false;
			break;
		case R.id.btn_history_toppage:
			Intent intent = new Intent(this, HistoryActivity.class);
			startActivityForResult(intent, HISTORY_REQUESTCODE);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			flag = false;
			break;
		default:
			break;
		}
	}

	/**
	 * Save status downloading DeckBean
	 */
	private void saveStatus() {
		SecurePreferences appPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		Gson gson = new Gson();
		Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() {
		}.getType();
		String save = gson.toJson(listDeckBean, listOfDeckBean);
		appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long arg3) {
		// TODO Auto-generated method stub
		if (flag == false)
			return;
		flag = false;
		selectedPosition = position;
		DeckBean deckBean;
		try {
			deckBean = listDeckBean.get(position);
		} catch (Exception ex) {
			flag = true;
			return;
		}
		switch (deckBean.deckId) {
		// case Special Deck
		case 999:
			if (deckBean.isUnlock) {
				if (setting.listSpecial == null
						|| setting.listSpecial.isEmpty()) {
					// goto setting special deck
					startActivityForResult(new Intent(this,
							SettingSpecialActivity.class), SETTING_REQUESTCODE);
					overridePendingTransition(R.anim.slide_in_right,
							R.anim.slide_out_left);
				} else {
					listDeckBean.get(position).lastUsedDate = new Date();
					saveStatus();
					passDeckToCardDeckActivity(deckBean);// goto card deck
				} // activity
			} else
				passDeck(deckBean); // go to info deck activity
			return;
			// case Random Deck
		case 998:
			if (deckBean.isUnlock) {
				// goto random card deck
				listDeckBean.get(position).lastUsedDate = new Date();
				saveStatus();
				//
				gotoRandomDeck();
			} else {
				// go to info deck
				passDeck(deckBean);
			}
			return;

		default:
			if (deckBean.percentDownloaded == -2) {
				listDeckBean.get(position).lastUsedDate = new Date();
				saveStatus();
				passDeckToCardDeckActivity(deckBean);
			} else
				passDeck(deckBean);
			break;
		}
	}

	void gotoRandomDeck() {
		ArrayList<DeckBean> list = new ArrayList<DeckBean>();
		for (DeckBean deck : listDeckBean) {
			if (deck.percentDownloaded == -2 || deck.deckId == 999)
				list.add(deck);
		}
		int size = list.size();
		Random random = new Random();
		DeckBean deckBean = list.get(random.nextInt(size));
		Intent intent = new Intent(this, RandomActivity.class);
		intent.putExtra("deckId", deckBean.deckId);
		intent.putExtra("deckName", deckBean.deckName);
		intent.putExtra("deckPrice", deckBean.deckPrice);
		intent.putExtra("deckPathServer", deckBean.pathServerDownload);
		intent.putExtra("position", selectedPosition);
		intent.putExtra("isUnlock", deckBean.isUnlock);
		intent.putExtra("cardTotal", deckBean.cardNumber);
		startActivityForResult(intent, RANDOM_REQUESTCODE);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		this.finish();
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		super.onPrepareDialog(id, dialog);
	}

	void showDialogDownloadError() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Creates textview for centre title
		TextView myMsg = new TextView(this);
		String title = getResources().getString(R.string.download_error);
		String message = getResources().getString(R.string.message_redownload);
		myMsg.setText(title);
		myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
		myMsg.setTextSize(20);
		myMsg.setTextColor(Color.WHITE);
		// set custom title
		builder.setCustomTitle(myMsg);
		builder.setMessage(message);
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	void showDialogSetting() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Creates textview for centre title
		TextView myMsg = new TextView(this);
		String title = getResources().getString(
				R.string.dialog_errornetwork_title);
		String message = getResources().getString(
				R.string.dialog_errornetwork_message);
		myMsg.setText(title);
		myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
		myMsg.setTextSize(20);
		myMsg.setTextColor(Color.WHITE);
		// set custom title
		builder.setCustomTitle(myMsg);
		builder.setMessage(message);
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("Setting",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
						startActivity(new Intent(
								android.provider.Settings.ACTION_SETTINGS));
					}
				});
		builder.show();
	}

	void backtoMainActivity() {
		Intent i = new Intent(this, MainActivity.class);
		startActivity(i);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		this.finish();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getStatus();
		flag = true;
		// Load new setting
		setting = ConstantValue.getSettingApp(this);
		listDeckBean = adapter.sortDeckBean(setting.sortToppage);
	}

	@Override
	public void onUpdateProgressListener(int percent, int position, int deckId) {
		// TODO Auto-generated method stub
		if (pDialog == null || !pDialog.isShowing())
			showDialogDownload();
		pDialog.setProgress(percent);
	}

	@Override
	public void onDownloadFailListener(DownloadUnzipObject object,
			String message) {
		// TODO Auto-generated method stub
		if (pDialog != null && pDialog.isShowing())
			pDialog.dismiss();
		if (message != null && message != "") {
			showDialog(message);
			return;
		}
		if (!NetworkUtils.isNetworkConnected(this)) {
			showDialogSetting();
		}
	}

	private void showDialog(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message);
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	@Override
	public void onFinishedListener(DownloadUnzipObject object) {
		// TODO Auto-generated method stub
		getStatus();
		if (pDialog != null && pDialog.isShowing())
			pDialog.dismiss();
		if (adapter != null)
			adapter.updateStatus(listDeckBean);
	}

	private void stopDownload() {
		Intent intentService = new Intent(this, ServiceDownload.class);
		intentService.putExtra("cancel", true);
		startService(intentService);
	}

	void showDialogDownload() {
		pDialog = new ProgressDialog(this);
		String message = getResources().getString(R.string.downloading_message);
		String button_cancle = getResources().getString(
				R.string.btn_cancle_download);
		pDialog.setMessage(message);
		pDialog.setIndeterminate(false);
		pDialog.setMax(100);
		pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pDialog.setCancelable(false);
		pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, button_cancle,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						stopDownload();
					}
				});
		pDialog.setProgress(0);
		pDialog.show();
	}
}
